﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using BusinessBingo.Common.Interfaces;
using BusinessBingo.Data.DataLoadOptions;
using BusinessBingo.Data.DataOrderOptions;
using BusinessBingo.Data.Filter;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;

namespace BusinessBingo.Data
{
    public class EFConferenceRepository : EFBaseRepository, IConferenceRepository
    {
        public EFConferenceRepository(IUnitOfWork unitOfWork, IGuid portalGuid)
            : base(unitOfWork, portalGuid)
        {
        }

        public IList<Model.Conference> GetItems(ConferenceDataLoadOptions dlo, ConferenceDataOrderOptions doo, ConferenceFilter filter)
        {
            ObjectQuery<Conference> query = this.GetQuery(dlo, doo, filter);
            IList<Conference> items = query.ToList();

            IList<Model.Conference> result = new List<Model.Conference>();

            foreach (Conference item in items)
            {
                result.Add(Mapping.MapConference(item));
            }

            return result;
        }
        
        public int GetItemsCount(ConferenceFilter filter)
        {
            ObjectQuery<Conference> query = this.GetQuery(null, null, filter);
            return query.Count();
        }

        public Model.Conference AddItem(Model.Conference item)
        {
            item.Id = this._portalGuid.New;

            Conference c = new Conference();
            c.Id = item.Id;
            c.Name = item.Name;

            this._context.Conferences.AddObject(c);

            return item;
        }

        public ObjectQuery<Data.Conference> GetQuery(ConferenceDataLoadOptions dlo, ConferenceDataOrderOptions doo, ConferenceFilter filter)
        {
            ObjectQuery<Conference> query = this._context.Conferences;

            return query.LoadWith(dlo).FilterFor(filter).OrderBy(doo);
        }
    }

    internal static class ConferenceQueryExtensions
    {
        public static ObjectQuery<Conference> FilterFor(this ObjectQuery<Conference> query, ConferenceFilter filter)
        {
            if (filter == null) return query;

            if (filter.WithId.HasValue == true)
                query = (ObjectQuery<Conference>)query.Where(x => x.Id.Equals(filter.WithId.Value));

            return query;
        }

        public static ObjectQuery<Conference> LoadWith(this ObjectQuery<Conference> query, ConferenceDataLoadOptions dlo)
        {
            ConferenceDataLoadOptions sdlo = (ConferenceDataLoadOptions)dlo;

            if (sdlo == null) return query;

            return query;
        }

        public static ObjectQuery<Conference> OrderBy(this ObjectQuery<Conference> query, ConferenceDataOrderOptions doo)
        {
            return query;
        }
    }
}